import multiprocessing


class PDControl(object):
    """位置式PD"""

    def __init__(self, model):
        self.s_r = None
        self.control_dic = None
        self.model = model
        self.Kp = None
        self.ki = None
        self.Kd = None
        self.delta_output = None
        self.d_change = None
        self.i_change = None
        self.p_change = None

        self.pid_out = 0

        self.pre_pre_error = 0
        self.pre_error = 0
        self.error = 0
        self.error_sum = 0

        self.count = 0

    def calculate(self, target, cur_val, s_r):

        self.error = target - cur_val
        self.error_sum = self.error_sum + self.error
        self.s_r = s_r
        self.pid_out = self.Kp * self.error + self.Ki * self.error_sum - self.Kd * self.s_r
        print("self.Kp:", self.Kp, "self.Kd:", self.Kd)
        # self.pid_out = self.Saturation(self.pid_out, 30, -30) * 81.7
        return self.pid_out

    def list_sum(self, list_input):
        list_sum = 0
        for i in range(len(list_input)):
            list_sum += list_input[i]

        return list_sum

    def set_pid(self):
        if self.model == 'A':
            self.Kp = float(self.control_dic['a_p'])
            self.Ki = float(self.control_dic['a_i'])
            self.Kd = float(self.control_dic['a_d'])
        elif self.model == 'V':
            self.Kp = float(self.control_dic['v_p'])
            self.Ki = float(self.control_dic['v_i'])
            self.Kd = float(self.control_dic['v_d'])
        elif self.model == 'D':
            self.Kp = 1.0
            self.Kd = 0.0
        else:
            self.Kp = 1.0
            self.Kd = 0.0
        print(f"PD:{self.Kp,  self.Kd}")

    def PID_clear(self):
        self.pre_pre_error = 0
        self.pre_error = 0
        self.error = 0
        self.pid_out = 0

    def Saturation(self, value, limit_up, limit_down):
        if value > limit_up:
            return limit_up
        elif value < limit_down:
            return limit_down
        else:
            return value





